﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;

namespace Q.Framework.Utility
{
    public static class DataReaderUtility
    {
        public static DataTable GetTable(DbDataReader dbReader)
        {
            DataTable schemaTable = dbReader.GetSchemaTable();
            DataTable outputTable = new DataTable();
            DataColumn dcColumn;
            DataRow drRow;

            for (int i = 0; i < schemaTable.Rows.Count; i++)
            {
                dcColumn = new DataColumn();
                if (!outputTable.Columns.Contains(schemaTable.Rows[i]["ColumnName"].ToString()))
                {
                    dcColumn.ColumnName = schemaTable.Rows[i]["ColumnName"].ToString();
                    dcColumn.Unique = Convert.ToBoolean(schemaTable.Rows[i]["IsUnique"]);
                    dcColumn.AllowDBNull = Convert.ToBoolean(schemaTable.Rows[i]["AllowDBNull"]);
                    dcColumn.ReadOnly = Convert.ToBoolean(schemaTable.Rows[i]["IsReadOnly"]);
                    outputTable.Columns.Add(dcColumn);
                }
            }

            while (dbReader.Read())
            {

                drRow = outputTable.NewRow();
                for (int i = 0; i < dbReader.FieldCount; i++)
                {
                    drRow[i] = dbReader.GetValue(i);
                }
                outputTable.Rows.Add(drRow);
            }

            return outputTable;
        }
    }
}
